package com.soft.small.app.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.soft.small.app.entity.AppClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttWireMessage;

@Data
@Slf4j
public class BaseService {
    public String getATCTopic(String sn, String model, String type){
        String tmp = "common/app/{}/{}/{}";
        return StrUtil.format(tmp,model,sn,type);
    }

    public String getATHTopic(String sn, String model, String type){
        String tmp = "host/app/{}/{}/{}";
        return StrUtil.format(tmp,model,sn,type);
    }

    public MqttWireMessage publishToHost(AppClient appClient,String model, String type, String data){
        String pubTopic = getATHTopic(appClient.getSn(),model,type);
        String pubMsg = getSendData(appClient,data);
        MqttWireMessage message = appClient.getMyMqttClient().publish(pubTopic,pubMsg);
        return message;
    }

    public void publishToCloud(AppClient appClient,String model, String type, String data){
        String pubTopic = getATCTopic(appClient.getSn(),model,type);
        String pubMsg = getSendData(appClient,data);
        appClient.getMyMqttClient().publish(pubTopic,pubMsg);
    }

    public JSONObject getHeader(AppClient appClient){
        String header = "{\"clientType\":\"uiot_app\",\"identity\":\"\",\"msgId\":\"\",\"appkey\":\"\",\"userUnique\":\"\",\"params\":{\"si\":\"\"},\"version\":\"1.0\",\"isEncrypt\":\"true\"}";
        JSONObject headerJson = JSONUtil.parseObj(header);
        headerJson.put("identity", appClient.getSi());
        headerJson.put("appkey", appClient.getAppKey());
        headerJson.put("userUnique", appClient.getUserUnique());
        JSONObject paramsJson = headerJson.getJSONObject("params");
        paramsJson.put("si",appClient.getSi());
        headerJson.put("params",paramsJson);
        long time = System.currentTimeMillis();
        headerJson.put("msgId",time+"");
        return headerJson;
    }

    public String getSendData(AppClient appClient,String data){
        JSONObject sendData = new JSONObject();
        sendData.put("header",getHeader(appClient));
        sendData.put("payload",JSONUtil.parseObj(data));
        return sendData.toString();
    }
}
